import type { App, Directive, DirectiveBinding } from 'vue'
import { useUserStore } from '@/stores/modules/user'

/**
 * 权限指令
 */
const permission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    const userStore = useUserStore()
    
    if (value && value instanceof Array && value.length > 0) {
      const permissions = userStore.permissions
      const hasPermission = value.some((permission: string) => {
        return permissions.includes(permission)
      })
      
      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(`需要设置权限标识，如 v-permission="['system:user:add']"`)
    }
  },
}

/**
 * 角色指令
 */
const role: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    const userStore = useUserStore()
    
    if (value && value instanceof Array && value.length > 0) {
      const roles = userStore.roles
      const hasRole = value.some((role: string) => {
        return roles.includes(role)
      })
      
      if (!hasRole) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(`需要设置角色标识，如 v-role="['admin']"`)
    }
  },
}

/**
 * 设置权限指令
 * @param app Vue应用实例
 */
export function setupPermissionDirective(app: App) {
  app.directive('permission', permission)
  app.directive('role', role)
}
